package com.prb.tomcat;

import com.prb.tomcat.container.Context;
import com.prb.tomcat.container.Host;
import com.prb.tomcat.handler.ServerHandler;
import com.prb.tomcat.servlet.IndexServlet;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Bootstrap {


    public void start(Integer port) throws IOException {

        init();

        // 初始化 ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress("localhost", port));
        ssc.configureBlocking(false);

        // 创建 Selector
        Selector selector = Selector.open();

        // 注册事件
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        while(true) {
            int readyNum = selector.select();
            if (readyNum == 0) {
                continue;
            }

            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectedKeys.iterator();
            while (it.hasNext()) {
                SelectionKey selectionKey = it.next();
                it.remove();

                if (selectionKey.isAcceptable()) {
                    SocketChannel socketChannel = ssc.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                } else if (selectionKey.isReadable()) {
                    // 处理请求
                    System.out.println("处理请求");
                    ServerHandler.INSTANCE.request(selectionKey);
                    selectionKey.interestOps(SelectionKey.OP_WRITE);
                } else if (selectionKey.isWritable()) {
                    // 响应请求
                    System.out.println("处理响应");
                    ServerHandler.INSTANCE.response(selectionKey);
                }
            }
        }



    }

    private void init() {

        Host host = new Host();
        Context context = new Context();
        host.setContext("/tomcat" , context);

        context.setServletHandler("/test" , new IndexServlet());

        ServerHandler.INSTANCE.setHost(host);

    }

    public void stop(){


    }


    public static void main(String[] args) throws IOException {

        new Bootstrap().start(8080);

    }

}
